package com.ftg.learn.service.impl;

import com.ftg.learn.comm.RMessCommEnum;
import com.ftg.learn.dto.TeacherSaveDto;
import com.ftg.learn.dto.TeacherUpdateDto;
import com.ftg.learn.entity.TeacherEntity;
import com.ftg.learn.mapper.TeacherMapper;
import com.ftg.learn.service.TeacherService;
import com.ftg.learn.util.PageEx;
import com.ftg.learn.util.R;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.SQLException;

/**
 * @author 布衣
 */
@Service
public class TeacherServiceImpl implements TeacherService {


    @Resource
    private TeacherMapper teacherMapper;

    @Override
    public R<PageEx<TeacherEntity>> getAll(Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        return R.ok(PageEx.convertToPageEx(new PageInfo<>(teacherMapper.getAll())));
    }

    @Transactional(rollbackFor = SQLException.class)
    @Override
    public R<Boolean> saveTeacher(TeacherSaveDto teacherEntity) {
        //参数合规校验 [如果在实体当中声明了就不用写了]
        if (teacherEntity.getTeaName().isEmpty() || teacherEntity.getTeaName().length() > 20) {
            return R.build(RMessCommEnum.R_SAVE_PARAMETER_ERROR);
        }

        if (teacherEntity.getTeaSex().isEmpty() || !(teacherEntity.getTeaSex().equals("男") || teacherEntity.getTeaSex().equals("女"))) {
            return R.build(RMessCommEnum.R_SAVE_PARAMETER_ERROR);
        }

        //业务逻辑校验  是否已存在

        int num = teacherMapper.saveTeacher(teacherEntity);

        return R.build(num > 0 ? RMessCommEnum.R_MESS_SUCCESS_ENUM : RMessCommEnum.R_MESS_FAILURE_ENUM);
    }

    @Transactional(rollbackFor = SQLException.class)
    @Override
    public R<Boolean> modifyTeacher(TeacherUpdateDto teacherEntity) {
        return R.build(teacherMapper.modifyTeacher(teacherEntity) > 0 ? RMessCommEnum.R_MESS_SUCCESS_ENUM : RMessCommEnum.R_MESS_FAILURE_ENUM);
    }

    @Transactional(rollbackFor = SQLException.class)
    @Override
    public R<Boolean> deleteTeacher(Integer id) {
        TeacherEntity t = teacherMapper.findOneById(id);
        if (t == null) {
            return R.build(RMessCommEnum.R_MESS_FAILURE_ENUM);
        }
        return R.build(teacherMapper.deleteById(id) > 0 ? RMessCommEnum.R_MESS_SUCCESS_ENUM : RMessCommEnum.R_MESS_FAILURE_ENUM);
    }

}
